layui.define(['jquery'], function(exports) {
    var $ = layui.$;
    var layrouter = {
        id: '',
        version: '1.0.0',
        // 路由表
        routes: [],
        view: function(content){
            var that = this;
            if(typeof content == 'string') {
                $(that.id).empty().append(content);
            }else{
                $.get(content.template, function(data){
                    $(that.id).empty().append(data);
                });
            }
        },
        // 注册路由
        register: function(hash, content) {
            var that = this;
            if (!hash) {
                return that;
            }
            var hash = that.realHash(hash);
            // 给不同的 hash 设置不同的回调函数
            if (typeof hash == 'string') {
                that.routes[hash] = function() {that.view(content)};
            } else if (hash instanceof Array) {
                // 路由数组
                for (var i in hash) {
                    that.register.apply(that, [].concat(hash[i]).concat(function() {that.view(content)}));
                }
            }
            return that;
        },
        realHash: function(hash) {
            var hash = hash || '/';
            var index = hash.indexOf('?');
            return hash.slice(0,index == -1 ? hash.length : index);
        },
        // 刷新
        refresh: function() {
            var that = this;
            var hash = location.hash.slice(1);
            var content = that.routes[that.realHash(hash)];
            content&&content();
        },
        // 初始化
        init: function(options) {
            var that = this;
            that.id = options.id || '';
            that.refresh();
            window.addEventListener('hashchange', that.refresh.bind(that), false);
            return that;
        },
        // 跳转
        go: function(hash) {
            var that = this;
            if (!hash) {
                return that;
            }
            window.location.hash = '#'.concat(hash);
            return that;
        }
    };
    exports('layrouter', layrouter);
});